package com.example.erp.service.permission.impl;

import cn.hutool.core.collection.CollUtil;
import com.example.erp.config.CommonConfig;
import com.example.erp.dto.permissionDTO.UserDTO;
import com.example.erp.dto.permissionDTO.UserEditPwdDTO;
import com.example.erp.dto.permissionDTO.UserRoleDTO;
import com.example.erp.mapper.permission.RoleMapper;
import com.example.erp.mapper.permission.UserMapper;
import com.example.erp.mapper.permission.UserRoleMapper;
import com.example.erp.pojo.permission.User;
import com.example.erp.service.permission.UserService;
import com.example.erp.utils.DataFormatUtils;
import com.example.erp.utils.RSAUtils;
import com.example.erp.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceA implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result list(UserDTO userDTO) {
        userDTO.setOffset((userDTO.getPageNum() - 1) * userDTO.getPageSize());
        List<User> list = userMapper.list(userDTO);
        list.forEach(it->{
            it.setImageList(DataFormatUtils.getListOfStr(it.getAvatar(), String.class));
            List<Long> roleIds = userRoleMapper.getRoleIdByUserId(it.getId());
            if(CollUtil.isNotEmpty(roleIds)){
                it.setRoleIds(roleIds);
                it.setRoleNames(roleMapper.getNameById(roleIds));
            }
        });

        Integer count = userMapper.count(userDTO);
        return Result.successMsg(Map.of(
                "rows", list,
                "total", count
        ));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(User user) {
        if(userMapper.getByName(user.getUsername()) != null){
            return Result.error(CommonConfig.resultMsg.USERNAMEQUERY.getDescription());
        };
        user.setAvatar(DataFormatUtils.getStrOfList(user.getImageList()));
        user.setPassword(passwordEncoder.encode("123456"));
        Integer count = userMapper.add(user);
        UserRole(user);
        if (count != null && count >= 1) {
            return Result.successMsg(user.getId(),CommonConfig.msgTYPE.ADD.getDescription());
        } else {
            return Result.error(CommonConfig.msgTYPE.ADDERR.getDescription());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result edit(User user) {
        if(userMapper.getByIdName(user.getId(),user.getUsername()) != null){
            return Result.error(CommonConfig.resultMsg.USERNAMEQUERY.getDescription());
        }
        user.setAvatar(DataFormatUtils.getStrOfList(user.getImageList()));
        Integer count = userMapper.edit(user);
        UserRole(user);
        if (count != null && count == 1) {
            return Result.successMsg(CommonConfig.msgTYPE.EDIT.getDescription());
        } else {
            return Result.error(CommonConfig.msgTYPE.EDITERROR.getDescription());
        }
    }

    @Override
    public Result editPwd(UserEditPwdDTO userEditPwdDTO,String token) {
        Long userId = DataFormatUtils.getTokenUser(token,"id");
        User user = userMapper.getById(userId);
        String oldPassword = RSAUtils.decrypt(userEditPwdDTO.getOldPassword());
        String newPassword = RSAUtils.decrypt(userEditPwdDTO.getNewPassword());
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return Result.error(CommonConfig.resultMsg.LOGINPWDQUERY.getDescription());
        }
        user.setPassword(passwordEncoder.encode(newPassword));
        Integer count = userMapper.edit(user);
        if (count != null && count == 1) {
            return Result.successMsg(CommonConfig.msgTYPE.EDIT.getDescription());
        } else {
            return Result.error(CommonConfig.msgTYPE.EDITERROR.getDescription());
        }
    }

    @Override
    public Result remove(List<Long> ids) {
        Integer count = userMapper.remove(ids);
        if (count != null && count  >= 1) {
            return Result.successMsg(CommonConfig.msgTYPE.REMOVE.getDescription());
        } else {
            return Result.error(CommonConfig.msgTYPE.REMOVEERROR.getDescription());
        }
    }

    public void UserRole(User user){
        List<Long> roleIds = user.getRoleIds();
        userRoleMapper.remove(user.getId());
        if(roleIds.size() > 0){
            List<UserRoleDTO> list = new ArrayList<>();
            for (Long id : roleIds){
                UserRoleDTO userRoleDTO = new UserRoleDTO(user.getId(),id,LocalDateTime.now());
                list.add(userRoleDTO);
            }
            userRoleMapper.batchInsert(list);
        }
    }
}
